package com.fitness.servlet;

import com.fitness.dao.ManagerDAO;
import com.fitness.dao.ProjectDAO;
import com.fitness.entity.Project;
import com.fitness.entity.ProjectManager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/ManagerServlet")
public class ManagerServlet extends HttpServlet {

    private final ManagerDAO managerDAO = new ManagerDAO();
    private final ProjectDAO projectDAO = new ProjectDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        if (action == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少 action 参数");
            return;
        }

        // 1. 处理【查询列表】逻辑
        if ("list".equals(action)) {
            List<ProjectManager> managerList = managerDAO.getManagerListWithProjectName();
            List<Project> projectList = projectDAO.getProjectList();

            request.setAttribute("managerList", managerList);
            request.setAttribute("projectList", projectList);
            request.setAttribute("managerDAO", managerDAO); // 用于JSP中判断项目是否已分配
            request.getRequestDispatcher("WEB-INF/views/admin/managerList.jsp").forward(request, response);
        }
        // 2. 处理【删除】逻辑
        else if ("delete".equals(action)) {
            try {
                int managerId = Integer.parseInt(request.getParameter("managerId"));
                boolean success = managerDAO.deleteManager(managerId);
                if (success) {
                    response.sendRedirect("ManagerServlet?action=list");
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "删除失败");
                }
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的经理 ID");
            }
        }
        else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "不支持的 action：" + action);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        if (action == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少 action 参数");
            return;
        }

        // 处理【新增】逻辑
        if ("add".equals(action)) {
            try {
                // 1. 接收并验证表单参数
                String managerName = request.getParameter("managerName");
                String projectIdStr = request.getParameter("responsibleProjectId");

                // 验证项目ID是否为空
                if (projectIdStr == null || projectIdStr.isEmpty()) {
                    request.setAttribute("errorMsg", "请选择负责项目！");
                    forwardToForm(request, response);
                    return;
                }

                int projectId = Integer.parseInt(projectIdStr);

                // 2. 验证项目是否已分配
                if (managerDAO.isProjectAssigned(projectId)) {
                    request.setAttribute("errorMsg", "该项目已分配项目经理，不能重复分配！");
                    forwardToForm(request, response);
                    return;
                }

                // 3. 插入新项目经理
                ProjectManager manager = new ProjectManager();
                manager.setManagerName(managerName);
                manager.setResponsibleProjectId(projectId);

                boolean success = managerDAO.insertManager(manager);
                if (success) {
                    response.sendRedirect("ManagerServlet?action=list");
                } else {
                    request.setAttribute("errorMsg", "新增项目经理失败，请稍后再试！");
                    forwardToForm(request, response);
                }
            } catch (NumberFormatException e) {
                request.setAttribute("errorMsg", "项目 ID 格式错误，请选择有效项目！");
                forwardToForm(request, response);
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("errorMsg", "系统错误，新增项目经理失败！");
                forwardToForm(request, response);
            }
        }
        else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "不支持的 action：" + action);
        }
    }

    // 转发回表单页并保持数据
    private void forwardToForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("managerList", managerDAO.getManagerListWithProjectName());
        request.setAttribute("projectList", projectDAO.getProjectList());
        request.setAttribute("managerDAO", managerDAO);
        request.getRequestDispatcher("WEB-INF/views/admin/managerList.jsp").forward(request, response);
    }
}